import { getLoginUserUsingGet } from '../api/userController'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  const token = ref(sessionStorage.getItem('token') || null)

  const setToken = (newToken: string) => {
    token.value = newToken
    sessionStorage.setItem('token', newToken)
  }

  const removeToken = () => {
    token.value = null
    sessionStorage.removeItem('token')
  }

  const loginUser = ref<any>({
    userName: '未登录',
  })

  function setLoginUser(newLoginUser: any) {
    loginUser.value = newLoginUser
  }
  async function fetchLoginUser() {
    const res = await getLoginUserUsingGet()
    if (res.data.code === 0 && res.data.data) {
      loginUser.value = res.data.data
    }
  }
  return { token, setToken, removeToken, loginUser, setLoginUser, fetchLoginUser }
})
